from flask import render_template, redirect, url_for, jsonify, request, session
from flask_login import login_user, logout_user, login_required, current_user 
from flask_bcrypt import check_password_hash, generate_password_hash
from app.auth import auth
from app.models import UserInformation
from app import db


@auth.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        if current_user.user_permission == "user":
            return redirect(url_for('user.index', username=current_user.user_name))
        else:
            return redirect(url_for('admin.admin_interface', username=current_user.user_name))
    return render_template('auth/login.html')


@auth.route('/login-post', methods=['POST'])
def login_post():
    message = {}
    username = request.form.get('username')
    password = request.form.get('password')

    if len(username) < 1 or len(username) > 64:
        message['info'] = "fail"
        message['message'] = "invalid username, 1 to 64 characters"
    elif len(password) < 6:
        message['info'] = "fail"
        message['message'] = "invalid password, at least 6 characters"
    else:
        # query user in the database
        user = UserInformation.query.filter_by(user_name=username).first()
        if user:
            if check_password_hash(user.user_password, password):
                login_user(user, remember=True)
                # success message and redirect to user/admin page(by sending url)
                message['info'] = "success"
                message['message'] = "Login Success"
                if (user.user_permission == "user"):
                    message['url'] = '/user/' + username
                else:
                    message['url'] = url_for('admin.admin_interface', username=username)
            else:
                message['info'] = "fail"
                message['message'] = "wrong password"
        else:
            message['info'] = "fail"
            message['message'] = "user does not exists"
    return jsonify(message)


@auth.route('/register', methods=['GET', 'POST'])
def register():
    return render_template('auth/register.html')


@auth.route('/register-post', methods=['POST'])
def register_post():
    message = {}
    username = request.form.get('username')
    password = request.form.get('password')
    permission = request.form.get('user_type')
    # query user in the database
    user = UserInformation.query.filter_by(user_name=username).first()
    if user:
        message['info'] = "fail"
        message['message'] = "user already exists, try another one"
    else:
        hashed = generate_password_hash(password)
        new_user = UserInformation(
            user_name = username,
            user_password = hashed,
            user_permission = permission
        )
        db.session.add(new_user)
        db.session.commit()
        # success message and redirect to login page(by sending url)
        message['info'] = "success"
        message['message'] = "Registeraton Success"
        message['url'] = url_for('auth.login')
    return jsonify(message)


@auth.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('auth.login'))